#!/bin/bash
#
# Setup QEMU emulation for arm linux on ubuntu
# 1. install QEMU
# 2. download and compile linux kernel
# 3. download and compile busybox, make rootfs based on busybox
# 4. run qemu-system-arm to emulate linux environment on versatile-express board. 

DIR=$(readlink -f $(dirname $0))
source $DIR/common.sh

# { [ -f fff ] && tar xf fff ; }  || { /bin/false || { echo "failed to dld " && exit 22 ; } ; }

${CROSS_COMPILE}gcc --version > /dev/null 2>&1 || { echo "Please install ${CROSS_COMPILE}gcc  first!" && exit 1 ; }

pushd $DIR

sudo apt-get install -y libglib2.0-dev libpixman-1-dev

qemu-system-arm --version >/dev/null 2>&1
if [ $? -eq 0 ]
then
	echo "QEMU has been installed, skip it"
else
	{ [ -f $QEMU_TARBALL ] && tar xf $QEMU_TARBALL ; } || { wget $QEMU_TARBALL_URL -O - | tar xf - || { echo "Failed to download qemu 3.0" && exit 1 ; } ; }
	echo "QEMU hasn't been installed, installing it ..."
	pushd $QEMU_PATH
	./configure --target-list=arm-softmmu && make -j4 && sudo make install
	popd
fi

{ [ -d $KERNEL_PATH ] || { [ -f $KERNEL_TARBALL ] && tar xf $KERNEL_TARBALL ; } ; } || { wget $KERNEL_TARBALL_URL -O - | tar xf - || { echo "Failed to download $KERNEL_TARBALL!" && exit 1 ; } ; }
pushd $KERNEL_PATH
make distclean && make $KERNEL_CONFIG && make -j8  || { echo "Failed to compile kernel" && exit 1 ; }
popd

{ [ -d $BUSYBOX_PATH ] || { [ -f $BUSYBOX_TARBALL ] && tar xf $BUSYBOX_TARBALL ; } ; }  || { wget $BUSYBOX_TARBALL_URL -O - | tar xf - || { echo "Failed to download $BUSYBOX_TARBALL" && exit 1 ; } ; }
./make_rootfs.sh ram

echo ""
echo "Setup complete!"
echo ""

./run.sh ram

popd

exit 0
